import fetch from '@system.fetch';
import http from '@ohos.net.http';
import util from './common/js/util.js';

export default {
    globalData: {
        domain: "http://101.35.249.138/back",
        token: null
    },
    onCreate() {
        console.info('=============AceApplication onCreate===============');
        this.login();
    },
    login: function () {
        let that = this;
        util.store.get(util.store.userKey).then(data => {
            if (data) {
                let user = JSON.parse(data)
                that.http({
                    url: `/login/in`,
                    data: user
                }).then(res => {
                    if (res.status == 200) {
                        that.globalData.token = res.data;
                    }
                })
            } else {
                let user = {
                    username: 'maofeng',
                    password: "123456"
                }
                that.http({
                    url: `/login/in`,
                    data: user
                }).then(res => {
                    if (res.status == 200) {
                        that.globalData.token = res.data;
                    }
                })
            }
        });

    },
    onDestroy() {
        //        console.info('AceApplication onDestroy');
    },
    http: function (config) {


        let that = this;
        if (!config.data) config.data = {};

        if (!config.method || config.method == 'GET') {


            if (!config.header) {
                config.header = {}
                config.header.token = this.globalData.token
            } else {
                config.header.token = this.globalData.token
            }

            // get 请求
            config.method = "GET";
            // 解析object为uri
            let params = "";
            let keys = Object.keys(config.data)

            if (keys && keys.length > 0) {
                for (let i = 0;i < keys.length; i++) {
                    params += keys[i]
                    params += "="
                    params += config.data[keys[i]]
                    if (i < keys.length - 1) {
                        params += "&"
                    }
                }
            }
            if (config.url.indexOf("?") < 0) {
                if (params != "") {
                    params = "?" + params
                }
            } else {
                if (params != "") {
                    params = "&" + params
                }
            }

            return new Promise((resolve, reject) => {
                fetch.fetch({
                    url: that.globalData.domain + config.url + params,
                    header: config.header,
                    responseType: "json",
                    success: function (res) {
                        //                        console.info(res)
                        let data;
                        if (typeof (res.data) == "string") {
                            data = JSON.parse(res.data);
                        }
                        resolve(data);
                    },
                    fail: function (error) {
                        console.error(JSON.stringify(error))
                        reject(error);
                    }
                });


            });
        }
        else {

            if (config.method == "POST" && !config.header) {
                config.header = {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'token': this.globalData.token
                    // 'Content-Type': 'form-data'
                }
            }
            return new Promise((resolve, reject) => {
                fetch.fetch({
                    url: that.globalData.domain + config.url,
                    data: config.data,
                    header: config.header,
                    method: config.method,
                    responseType: "json",
                    success: function (res) {
                        let data;
                        if (typeof (res.data) == "string") {
                            data = JSON.parse(res.data);
                        }
                        resolve(data);
                    },
                    fail: function (error) {
                        reject(error);
                    }
                });


            });


        }
    }
};


/*        httpRequest.request(
                // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
                    that.globalData.domain + config.url,
                    {
                        method: config.method, // 可选，默认为“GET”
                        // 开发者根据自身业务需要添加header字段
                        header: config.header,
                        // 当使用POST请求时此字段用于传递内容
                        extraData: config.data,
                        readTimeout: 60000, // 可选，默认为60000ms
                        connectTimeout: 60000 // 可选，默认为60000ms
                    },
                    (err, data) => {
                        if (!err) {
                            // data.result为http响应内容，可根据业务需要进行解析
                            console.info('Result:' + data.result);

                            resolve(JSON.parse(data.result));

                            console.info('code:' + data.responseCode);
                            // data.header为http响应头，可根据业务需要进行解析
                            console.info('header:' + data.header);
                        } else {
                            console.info('error:' + err.data);
                            reject(err.data);
                        }
                    }
                );*/

/*

                let httpRequest = http.createHttp();
                console.info(that.globalData.domain + config.url + params);

                httpRequest.request(
                    that.globalData.domain + config.url + params,
                    {
                        method: http.RequestMethod.GET,
                        header: {},
                        readTimeout: 60000,
                        connectTimeout: 60000
                    },
                    (err, data) => {
                        console.info(error);
                        console.info(data);

                        if (!err) {
                            console.info(data);

                            // data.result为http响应内容，可根据业务需要进行解析
                            console.info('Result:' + data.result);

                            console.info('code:' + data.responseCode);
                            // data.header为http响应头，可根据业务需要进行解析
                            console.info('header:' + data.header);

                            resolve(JSON.parse(data.result));

                        } else {
                            console.error('error:' + err.data)
                            console.error("=========http error===========")
                            reject(err.data);
                        }
                    }
                );*/
